<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="formData.orderNo" placeholder="请输入订单号" />
      </el-form-item>
      <el-form-item label="用户编号" prop="userId">
        <el-input v-model="formData.userId" placeholder="请输入用户编号" />
      </el-form-item>
      <el-form-item label="联系人" prop="userName">
        <el-input v-model="formData.userName" placeholder="请输入联系人姓名" />
      </el-form-item>
      <el-form-item label="联系电话" prop="userPhone">
        <el-input v-model="formData.userPhone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item label="物品类型" prop="itemTypeId">
        <el-tree-select
          v-model="formData.itemTypeId"
          :data="typeTreeData"
          :props="treeProps"
          check-strictly
          placeholder="请选择回收类型"
          class="w-full"
          clearable
          filterable
          :render-after-expand="false"
        />
      </el-form-item>
      <el-form-item label="物品描述" prop="itemDesc">
        <el-input v-model="formData.itemDesc" placeholder="请输入物品描述" />
      </el-form-item>
      <el-form-item label="预约时间" prop="appointmentTime">
        <el-date-picker
          v-model="formData.appointmentTime"
          type="datetime"
          value-format="x"
          placeholder="请选择预约时间"
          :default-value="new Date()"
          :default-time="new Date()"
        />
      </el-form-item>
      <el-form-item label="回收人员" prop="collectorId">
        <el-select
          v-model="formData.collectorId"
          placeholder="请选择回收人员"
          filterable
          clearable
          class="w-full"
        >
          <el-option
            v-for="item in collectorOptions"
            :key="item.id"
            :label="`${item.name}`"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择订单状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.RECYCLING_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注信息" prop="remarks">
        <el-input v-model="formData.remarks" placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { OrderApi, OrderVO } from '@/api/recycl/order'
import { ItemTypeApi } from '@/api/recycl/Itemtype' // 确保路径正确
import { handleTree } from '@/utils/tree' // 树形数据处理工具
import { CollectorApi } from '@/api/recycl/collector'

const collectorOptions = ref<any[]>([]) // 存储回收人员选项
const typeTreeData = ref<any[]>([]) // 树形分类数据
const treeProps = { // 树形组件配置
  value: 'id',
  label: 'name',
  children: 'children'
}

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 新增：获取分类数据
  try {
    const  data  = await ItemTypeApi.getItemTypeList({})
    typeTreeData.value = handleTree(data, 'id', 'parentId')
  } catch (e) {
    console.error('获取分类数据失败:', e)
  }

  try {
    const { list } = await CollectorApi.getCollectorPage({
      pageNo: 1,
      pageSize: 100, // 获取全量数据
      status: 0 // 可选：只显示在岗人员
    })
    collectorOptions.value = list
  } catch (e) {
    console.error('获取回收人员数据失败:', e)
    message.error('回收人员数据加载失败')
  }

  // 原有数据加载逻辑
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderApi.getOrder(id)
    } finally {
      formLoading.value = false
    }
  }
}

/** 回收订单 表单 */
defineOptions({ name: 'OrderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  orderNo: undefined,
  userId: undefined,
  userName: undefined,
  userPhone: undefined,
  address: undefined,
  itemTypeId: undefined,
  itemDesc: undefined,
  appointmentTime: undefined,
  collectorId: undefined,
  status: undefined,
  remarks: undefined,
})
const formRules = reactive({
  orderNo: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '用户编号不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '订单状态不能为空', trigger: 'change' }],
  itemTypeId: [{
    required: true,
    message: '请选择回收物品类型', // 修改提示语
    trigger: 'change' // 建议改为 change 事件
  }],
  collectorId: [{
    required: true,
    message: '请选择回收人员',
    trigger: 'change' // 建议改为 change 事件
  }],
  userPhone: [
    { required: true, message: '联系电话不能为空', trigger: 'blur' },
    {
      pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
      message: '请输入有效的手机号码',
      trigger: 'blur'
    }
  ],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrderVO
    if (formType.value === 'create') {
      await OrderApi.createOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderApi.updateOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    orderNo: undefined,
    userId: undefined,
    userName: undefined,
    userPhone: undefined,
    address: undefined,
    itemTypeId: undefined,
    itemDesc: undefined,
    appointmentTime: undefined,
    collectorId: undefined,
    status: undefined,
    remarks: undefined,
  }
  formRef.value?.resetFields()
}
</script>
